<template>
	<view class="tutorial-container">
		<rich-text :nodes="tutorialNodes" space="nbsp" :selectable="false" :image-menu-prevent="true" :preview="false" @itemclick="onInteractiveItemClick"></rich-text>
	</view>
</template>

<script>
export default {
	data() {
		return {
			tutorialNodes: []
		};
	},
	onLoad() {
		// **关键点**：定义结构化的业务Mock数据，而非直接定义nodes
		const tutorialMockData = {
			title: 'Git入门三步走',
			steps: [
				{ type: 'text', content: '第一步：初始化你的项目仓库。请点击下方命令以复制：' },
				{
					type: 'command',
					action: 'copy-command',
					command: 'git init'
				},
				{
					type: 'text',
					content: '这个技巧由我们的社区大神 '
				},
				{
					type: 'mention',
					action: 'show-user-profile',
					userId: 'git_master_007',
					displayText: '@Git老司机'
				},
				{
					type: 'text',
					content: ' 贡献。'
				}
			]
		};

		// 调用生成器函数，将业务数据转换为视图节点
		this.tutorialNodes = this.generateNodesFromData(tutorialMockData);
	},
	methods: {
		// **关键实践**：将业务逻辑数据转换为nodes数组的“工厂函数”
		generateNodesFromData(data) {
			const nodes = [];
			const p_children = [];

			data.steps.forEach((step) => {
				switch (step.type) {
					case 'text':
						p_children.push({ type: 'text', text: step.content });
						break;
					case 'command':
						p_children.push({
							name: 'a', // 使用<a>标签使其可点击
							attrs: {
								class: 'command-block',
								'data-action': step.action,
								'data-command': step.command
							},
							children: [{ type: 'text', text: step.command }]
						});
						break;
					case 'mention':
						p_children.push({
							name: 'a',
							attrs: {
								class: 'mention',
								'data-action': step.action,
								'data-userid': step.userId
							},
							children: [{ type: 'text', text: step.displayText }]
						});
						break;
				}
			});

			// 将所有内容包裹在一个<p>标签内
			nodes.push({ name: 'p', attrs: { class: 'tutorial-paragraph' }, children: p_children });

			return nodes;
		},
		onInteractiveItemClick(e) {
			const { node } = e.detail;
			const attrs = node.attrs;

			switch (attrs['data-action']) {
				case 'copy-command':
					uni.setClipboardData({ data: attrs['data-command'], success: () => uni.showToast({ title: '命令已复制' }) });
					break;
				case 'show-user-profile':
					uni.showModal({ title: '用户信息', content: `即将查看用户 ${attrs['data-userid']} 的主页。` });
					break;
			}
		}
	}
};
</script>

<style scoped>
.command-block {
	background-color: #2c3e50;
	color: #fff;
	padding: 8px;
	border-radius: 4px;
	font-family: monospace;
	margin: 5px 0;
	display: block; /* 使其独占一行 */
}
.mention {
	color: #007aff;
	font-weight: bold;
}
</style>
